import { each, get, set } from 'lodash';
import { toJS } from 'mobx';
import { ViewUrl } from '../../../constants/excel';
import route from '../../../constants/route';
import API from '../../../apis/excel';
import CellType from '../celltypes';
import getPinyin from '../../../utils/getPy';
import { WeaCheckbox } from 'ecCom';
import getBorderedColRanges, { getNextColBorderedRanges } from '../../../utils/getBorderedColRanges';
import { Button, message, Modal } from 'antd';
import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;

export function importFile(file) {
    this.loadFile(file, file.name.replace('.xlsx', ''));
}
export function hideQuickTable() {
    this.quickTableVisible = false;
}
export function expandCell() {
    const sheet = this.workbook.getActiveSheet();
    sheet.suspendPaint();
    sheet.setColumnCount(sheet.getColumnCount() + 50);
    sheet.setRowCount(sheet.getRowCount() + 20);
    sheet.resumePaint();
}
export function changeCellStyle(obj) {
    const sheet = this.workbook.getActiveSheet();
    sheet.suspendPaint()
    const selections = sheet.getSelections();
    const sheetName = sheet.name();
    each(obj, (v, key) => {
        const actionName = `set${key.charAt(0).toUpperCase()}${key.substring(1)}`;
        this.workbook.commandManager().execute({
            autoFitType: GC.Spread.Sheets.AutoFitType.cell,
            cmd: actionName,
            selections,
            [key]: v,
            sheet,
            sheetName,
        });
    });
    sheet.resumePaint();
}
export function combindCellType(cellType, fieldType) {
    const [type] = fieldType;

    if (type == 'select') {
        cellType.fieldType = ['select', 'select', cellType.fieldType[2]];
    } else {
        cellType.fieldType = fieldType;
    }
    if (fieldType === void 0) {
        return undefined;
    }
    return cellType;
}
export function changeCellType(fieldType) {
    const sheet = this.workbook.getActiveSheet();
    const sheetIndex = this.workbook.getSheetIndex(name);
    const selections = sheet.getSelections();

    const openSelectOptionsDialog = (datas, relatedChild, button, bool) => {
        this.addSelectOptionsStore.fieldType = 'select';
        if (bool) {
            this.addSelectOptionsStore.open();

            const { row, col } = selections[0];
            const table = sheet.tables.find(row, col);
            let bindingPath = "";
            let fieldName = "";
            let istable = 0;
            if (table) {
                fieldName = table.getColumnDataField(col - table.dataRange().col);
                bindingPath = table.bindingPath();
                istable = 1;

            } else {
                const path = sheet.getBindingPath(row, col);
                if (path) {

                    const [sheetName, fName] = path.split('.');
                    bindingPath = sheetName;
                    fieldName = fName;
                } else {
                    bindingPath = this.workbook.getActiveSheet().name();
                }
            }

            this.addSelectOptionsStore.initOptions(datas, relatedChild, bindingPath, fieldName,istable);
            this.addSelectOptionsStore.buttons[1] = button;
        } else {
            this.addSelectOptionsStore.hide();
            this.addSelectOptionsStore.datas = [];
        }
    }
    const getSelectOptionsDatas = () => {
        return this.addSelectOptionsStore.datas;
    }
    const getSelectedRelatedChild = () => {
        return this.addSelectOptionsStore.relatedChild;
    }

    const refreshSelectCelltypes = () => {
        this.getSelectCelltypes();
    }

    const doCheck = () => {
        const size = (this.addSelectOptionsStore.datas || []).length;
        const count = (this.addSelectOptionsStore.datas || []).filter( r => r.selectName).length;
        console.log(size, count)
        if(size >count) {
            message.error("可选项文字不能为空!");
            return false;
        } else {
            return true;
        }
    }
    this.workbook.commandManager().execute({
        autoFitType: GC.Spread.Sheets.AutoFitType.cell,
        cmd: 'changeCellType',
        selections,
        sheet,
        sheetIndex,
        sheetName: sheet.name(),
        fieldType,
        openSelectOptionsDialog,
        getFieldIndex: this.getFieldIndex,
        getMainTableFieldName: this.getMainTableFieldName,
        getFieldName: this.getFieldName,
        getSelectOptionsDatas,
        getSelectedRelatedChild,
        refreshSelectCelltypes,
        doCheck
    });

}

function treeToList(tree) {
    var queen = [];
    var out = [];
    queen = queen.concat(...tree.filter(r => { return r.deleted != true }));

    while (queen.length) {
        var first = queen.shift();
        if (first.subs) {
            queen = [...first.subs].concat(queen);
        }
        if (first.deleted) {

            continue;
        }
        out.push(first);
    }
    return out;
}

export function setSelectFillIn() {
    const sheet = this.workbook.getActiveSheet();

    const selections = sheet.getSelections();
    this.browserAutoFillin = true;

    const { row, col, rowCount, colCount } = selections[0];
    const cellType = sheet.getCell(row, col).cellType();
    const fieldType = cellType.fieldType;
    const length = fieldType.length;

    const save = () => {
        const data = toJS(this.addFixphareStore.datas);
        if (!data || data.length == 0) {
            this.browserAutoFillin = false;
        }
        this.setAutoFillin(this.browserAutoFillin);
        sheet.getCell(row, col).cellType().fieldType[3] = data;

        this.addFixphareStore.hide();
        this.addFixphareStore.datas = [];
    }

    const reset = () => {
        const data = [];
        this.browserAutoFillin = false;

        this.setAutoFillin(this.browserAutoFillin);
        sheet.getCell(row, col).cellType().fieldType[3] = data;

        this.addFixphareStore.hide();
        this.addFixphareStore.datas = [];
    }
    this.addFixphareStore.oraginValue = (sheet.getCell(row, col).cellType().fieldType[2] || {}).datas;
    let datas = length > 3 ? sheet.getCell(row, col).cellType().fieldType[3] : [];
    if (!datas) {
        datas = [];
    }


    this.addFixphareStore.fieldType = 'select';
    this.addFixphareStore.sheet = sheet;
    this.addFixphareStore.row = row;
    this.addFixphareStore.col = col;
    //this.addFixphareStore.browserSetting();
    this.addFixphareStore.open();
    this.addFixphareStore.initOptions(datas);
    this.addFixphareStore.buttons[1] = (<Button key="reset" onClick={reset} type="primary">清空</Button>);
    this.addFixphareStore.buttons[2] = (<Button key="ok" onClick={save} type="primary">{getLabel('30986', '保存')}</Button>);
}

export function setFillInData() {
    const sheet = this.workbook.getActiveSheet();

    const selections = sheet.getSelections();
    this.browserAutoFillin = true;

    const { row, col, rowCount, colCount } = selections[0];
    const cellType = sheet.getCell(row, col).cellType();
    const fieldType = cellType.fieldType;
    const length = fieldType.length;
    // if(!bool) {
    //     sheet.getCell(row,col).cellType().fieldType[3] = "";
    //     return;
    // }
    if (length == 2) {
        sheet.getCell(row, col).cellType().fieldType[2] = "";
    }

    if (fieldType[1] && (fieldType[1].value == '256' || fieldType[1].value == '257')) {
        const save = () => {
            let datas = this.addSelectTreeStore.datas;
            if (datas) {
                let res = [];
                //datas = datas.map(d => ({ selectValue: d.id, selectName: d.name }));
                datas = treeToList(datas);
                datas = datas.map(d => ({ selectValue: d.id, selectName: d.name, pid: d.pid }));
                if (!datas || datas.length == 0) {
                    this.browserAutoFillin = false;
                }

            } else {
                this.browserAutoFillin = false;
            }
            this.setAutoFillin(this.browserAutoFillin);
            sheet.getCell(row, col).cellType().fieldType[3] = toJS(datas);

            this.addSelectTreeStore.hide();
            this.addSelectTreeStore.datas = [];
        }

        const reset = () => {
            let datas = [];
            this.browserAutoFillin = false;

            this.setAutoFillin(this.browserAutoFillin);
            sheet.getCell(row, col).cellType().fieldType[3] = toJS(datas);

            this.addSelectTreeStore.hide();
            this.addSelectTreeStore.datas = [];
        }

        let datas = length == 4 ? sheet.getCell(row, col).cellType().fieldType[3] : [];
        if (!datas) {
            datas = [];
        }

        this.addSelectTreeStore.fieldType = 'browser';
        this.addSelectTreeStore.sheet = sheet;
        this.addSelectTreeStore.row = row;
        this.addSelectTreeStore.col = col;
        this.addSelectTreeStore.browserSetting();
        this.addSelectTreeStore.open();
        this.addSelectTreeStore.initOptions(datas);
        this.addSelectTreeStore.buttons[1] = (<Button key="reset" onClick={reset} type="primary">清空</Button>);
        this.addSelectTreeStore.buttons[2] = (<Button key="ok" onClick={save} type="primary">{getLabel('30986', '保存')}1</Button>);

        return;
    }

    //addSelectTreeStore

    const save = () => {
        const data = toJS(this.addFixphareStore.datas);
        if (!data || data.length == 0) {
            this.browserAutoFillin = false;
        }
        this.setAutoFillin(this.browserAutoFillin);
        sheet.getCell(row, col).cellType().fieldType[3] = data;

        this.addFixphareStore.hide();
        this.addFixphareStore.datas = [];
    }

    const reset = () => {
        const data = [];
        this.browserAutoFillin = false;
        this.setAutoFillin(this.browserAutoFillin);
        sheet.getCell(row, col).cellType().fieldType[3] = data;

        this.addFixphareStore.hide();
        this.addFixphareStore.datas = [];
    }

    let datas = length == 4 ? sheet.getCell(row, col).cellType().fieldType[3] : [];
    if (!datas) {
        datas = [];
    }

    this.addFixphareStore.fieldType = 'browser';
    this.addFixphareStore.sheet = sheet;
    this.addFixphareStore.row = row;
    this.addFixphareStore.col = col;
    this.addFixphareStore.browserSetting();
    this.addFixphareStore.open();
    this.addFixphareStore.initBrowserOptions(datas);
    this.addFixphareStore.buttons[1] = (<Button key="reset" onClick={reset} type="primary">清空</Button>);
    this.addFixphareStore.buttons[2] = (<Button key="ok" onClick={save} type="primary">{getLabel('30986', '保存')}</Button>);

}

export function preview() {
    window.open(`${ViewUrl}#/${route.excelView}?pageid=${this.page.id}`)
}

export function saveExcelPage() {
    this.loading = true;
    const { id: pageid = '', templateid = '', name = this.parent().app.name } = this.page || {}
    API.saveFormAndField({
        appid: this.appid,
        pageid,
        name,
        json: JSON.stringify(this.workbook.toJSON()),
        nodetailJson: JSON.stringify(this.nodetailJson),
        templateid,
        rowControl: JSON.stringify(this.rowControl),
    }).then(this.afterSave);
}
export function afterSave(page) {
    this.loading = false;
    message.config({ top: 60 });
    message.success(getLabel('502231', '保存成功'));
    this.showPage(page);
    this.reloadHeadTabs(page);
}
export function getDetailIndex(mainTable, sheet) {
    if (this.detailIndex[mainTable] !== void 0) {
        this.detailIndex[mainTable] = this.detailIndex[mainTable] + 1;
    } else {
        this.detailIndex[mainTable] = 1;
    }
    const detailIndex = this.detailIndex[mainTable];
    if (sheet) {
        if (sheet.tables.findByName(`detail${detailIndex}`)) {
            return this.getDetailIndex(mainTable, sheet);
        }
    }
    return detailIndex;
}
export function loadTemplate(template) {
    if (template) {
        this.showPage({
            json: template.json ? template.json : {},
            labels: {},
            fieldName: {},
            name: template.name,
            templateid: template.id,
        });

        this.templateJSON = this.workbook.toJSON();
    }
}
export function loadFile(file, name) {
    const excelIO = new GC.Spread.Excel.IO();
    excelIO.open(
        file,
        json => {
            this.showPage({
                json: json,
                labels: {},
                fieldName: {},
                name
            });
            this.templateJSON = json;
            this.templateBrowserStore.hide();
        },
        (error) => {
            message.error(error);
            this.loading = false;
        }
    );
}

export function exportExcel(title, json) {
    const excelIO = new GC.Spread.Excel.IO();
    excelIO.save(json, (blob) => {
        saveAs(blob, `${title}.xlsx`);
        this.init(this.params);
        resolve();
    }, function (e) {
        if (!!(window.console && window.console.log)) {
            window.console.log(e);
        }
        this.init(this.params);
        resolve();
    });
}

export function restore(json) {
    this.showPage({ ...this.page, json });
}
export function autoSignFields() {
    const sheet = this.workbook.getActiveSheet();
    this.workbook.commandManager().execute({
        autoFitType: GC.Spread.Sheets.AutoFitType.cell,
        cmd: 'autoSignField',
        store: this,
        sheet,
        sheetName: sheet.name(),
    });
}
export function signFields() {
    if (this.mainTables.length > 0) {
        Modal.confirm({
            content: getLabel('502902', '字段识别将清除所有字段，请确认是否继续'),
            onOk: this.doSignFields,
            title: getLabel('502903', '信息确认')
        })
    } else {
        this.doSignFields();
    }
}
const getFieldCellType = (field) => {
    const FieldCellType = CellType('FieldCellType');
    const fieldCellType = new FieldCellType();
    fieldCellType.fieldType = field.fieldType;
    fieldCellType.detailIndex = field.detailIndex;
    fieldCellType.fieldName = field.fieldName;
    fieldCellType.fieldIndex = field.fieldIndex;
    fieldCellType.label = field.label;
    return fieldCellType;
}
export function doSignFields() {
    this.loading = true;
    this.oldJSON = this.workbook.toJSON();
    if (this.templateJSON) {

        this.workbook.fromJSON(this.templateJSON, false);
    }

    this.clearFields();
    this.workbook.sheets.forEach((sheet, sheetIndex) => {
        const sheetName = sheet.name();
        const mainTableObj = {
            detailTables: [],
            fields: [],
            tableName: `${this.title}${sheetName}`,
            sheetName
        }

        const mainTable = `mainTable_${sheetIndex}`;
        const maxRowCount = sheet.getRowCount();
        const maxColCount = sheet.getColumnCount();

        sheet.tables.all().sort((a, b) => {
            const { row: arow, col: acol } = a.dataRange();
            const { row: brow, col: bcol } = b.dataRange();

            let diff = arow - brow;
            if (diff == 0) {
                diff = acol - bcol;
            }
            return diff;
        }).forEach(table => {
            const { colCount } = table.range();
            const { row: dataRow, col: dataCol } = table.dataRange();
            const detailIndex = this.getDetailIndex(mainTable);
            const detail = `detail_${detailIndex}`;
            const detailFields = [];
            table.name(`detail${detailIndex}`);
            table.bindingPath(`${sheetName}.${detail}`);
            for (let index = 0; index < colCount; index++) {
                let label = table.getColumnName(index);
                const fieldIndex = this.getFieldIndex(mainTable, detail);
                let fieldName;
                if (label) {
                    fieldName = getPinyin(label)[0];
                } else {
                    label = `${getLabel(502711, '字段') + fieldIndex}`;
                }
                if (!fieldName) {
                    fieldName = `field${fieldIndex}`;
                }
                fieldName = this.getFieldName(mainTable, detail, fieldName).toLowerCase();
                table.setColumnDataField(index, fieldName);

                detailFields.push({
                    col: dataCol + index,
                    colCount: 1,
                    fieldName,
                    fieldType: ['input', 'text', '200'],
                    label,
                    row: dataRow,
                    rowCount: 1,
                    detailIndex
                });
            }

            mainTableObj.detailTables.push({
                ...table.range(),
                detailIndex,
                fields: detailFields,
            });
        });

        for (let rowIndex = 0; rowIndex < maxRowCount; rowIndex++) {
            for (let colIndex = 0; colIndex < maxColCount; colIndex++) {
                if (sheet.tables.find(rowIndex, colIndex)) {
                    continue;
                }

                let currentCell;
                const span = sheet.getSpan(rowIndex, colIndex);
                if (span) {
                    if (span.row !== rowIndex || span.col !== colIndex) {
                        continue;
                    }
                    currentCell = sheet.getRange(span.row, span.col, span.rowCount, span.colCount);
                } else {
                    currentCell = sheet.getCell(rowIndex, colIndex);
                }
                const isInDetails = this.isInDetails.bind(this, mainTableObj);
                let rangeRowCounts = [];
                let rangeRowCounts1 = getBorderedColRanges(sheet, currentCell, isInDetails);
                let range1 = currentCell;
                const rangeColCounts = [];
                while (rangeRowCounts1.length > 2) {
                    rangeRowCounts = rangeRowCounts1;
                    rangeColCounts.push(range1.colCount)
                    const [rangeRowCountsTemp, rangeTemp] = getNextColBorderedRanges(sheet, range1, rangeRowCounts1, isInDetails);
                    rangeRowCounts1 = rangeRowCountsTemp;
                    range1 = rangeTemp;
                }
                if (rangeColCounts.length > 1 && rangeRowCounts.length > 2) {
                    const sum = (...args) => {
                        let rt = 0;
                        args.map(n => {
                            rt += n;
                        });
                        return rt;
                    }
                    const detailIndex = this.getDetailIndex(mainTable);
                    const tempDetail = `detail_${detailIndex}`;
                    const detailRowCount = sum(...rangeRowCounts);
                    const detailColCount = sum(...rangeColCounts);
                    const detailTable = {
                        col: currentCell.col,
                        colCount: detailColCount,
                        detailIndex,
                        fields: [],
                        row: currentCell.row,
                        rowCount: detailRowCount,
                    };
                    mainTableObj.detailTables.push(detailTable);
                    let tempCol = currentCell.col;
                    const tempRow = currentCell.row + rangeRowCounts[0];
                    const tempStartRow = currentCell.row;
                    rangeColCounts.forEach(tempColCount => {
                        let templabel = sheet.getRange(tempStartRow, tempCol).value();
                        const tempFieldIndex = this.getFieldIndex(mainTable, tempDetail);
                        if (!templabel) {
                            templabel = `${getLabel(502711, '字段') + tempFieldIndex}`;
                        }
                        const tempFieldName = this.getFieldName(mainTable, "mainTable", getPinyin(templabel)[0]);
                        detailTable.fields.push({
                            col: tempCol,
                            colCount: tempColCount,
                            fieldName: tempFieldName,
                            fieldType: ['input', 'text', '200'],
                            label: templabel,
                            row: tempRow,
                            rowCount: detailRowCount[1],
                            detailIndex: detailTable.detailIndex
                        });
                        tempCol += tempColCount;
                    });

                    const table = sheet.tables.add(`detail${detailIndex}`, rowIndex, colIndex, detailRowCount, detailColCount);
                    table.filterButtonVisible(false);
                    table.bindingPath(`${sheetName}.${tempDetail}`);
                    const columns = detailTable.fields.map(field => (
                        new GC.Spread.Sheets.Tables.TableColumn(field.fieldName).name(field.label).dataField(field.fieldName)
                    ));
                    table.bindColumns(columns);
                }
                if (isInDetails(rowIndex, colIndex)) {
                    continue;
                }
                if (currentCell.value()) {
                    continue;
                }

                if (!!currentCell.borderBottom()) {
                    const fieldIndex = this.getFieldIndex(mainTable, "mainTable");
                    const label = this.getMainTableFieldName(sheet, rowIndex, colIndex, fieldIndex);
                    const fieldName = this.getFieldName(mainTable, "mainTable", getPinyin(label)[0]).toLowerCase();
                    currentCell.bindingPath(`${sheetName}.${fieldName}`);
                    mainTableObj.fields.push({
                        col: colIndex,
                        colCount: currentCell.colCount,
                        fieldName,
                        fieldType: ['input', 'text', '200'],
                        label,
                        row: rowIndex,
                        rowCount: currentCell.rowCount,
                    });
                }
            }
        }
        if (mainTableObj.detailTables.length > 0 || mainTableObj.fields.length > 0) {
            this.mainTables.push(mainTableObj);
        }
    });

    let detailSize = 0;
    let fieldSize = 0;
    this.mainTables.forEach(d => {
        detailSize += d.detailTables.length;
        fieldSize += d.fields.length;
        d.detailTables.forEach(dt => {
            fieldSize += dt.fields.length;
        });
    });


    Modal.confirm({
        content: `${getLabel('502904', '识别到') + this.mainTables.length + getLabel('502905', '个主表,')}${detailSize + getLabel('502906', '个明细表，共计') + fieldSize + getLabel('502907', '个字段，请确认是否应用识别的字段')}`,
        onCancel: () => {
            this.clearFields();
            this.workbook.fromJSON(this.oldJSON, false);
        },
        onOk: () => {
            this.workbook.suspendPaint();
            this.mainTables.forEach((mainTable, tableIndex) => {
                const sheet = this.workbook.getSheetFromName(mainTable.sheetName);
                if (sheet) {
                    mainTable.fields.forEach((field, index) => {
                        const fieldCellType = getFieldCellType(field);
                        sheet.getCell(field.row, field.col)
                            .textIndent(2.5)
                            .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none)
                            .backgroundImage(fieldCellType.getFieldTypeImage())
                            .cellType(fieldCellType);
                    });
                    mainTable.detailTables.forEach((detailTable, detailIndex) => {
                        detailTable.fields.forEach((detailField, detailFieldIndex) => {
                            const fieldCellType = getFieldCellType(detailField);
                            sheet.getCell(detailField.row, detailField.col)
                                .textIndent(2.5)
                                .backgroundImageLayout(GC.Spread.Sheets.ImageLayout.none)
                                .backgroundImage(fieldCellType.getFieldTypeImage())
                                .cellType(fieldCellType);
                        });
                    });

                }
            });
            this.workbook.resumePaint();
            this.loading = false;
        },
        title: getLabel('502903', '信息确认'),
    });
}
export function clearFields() {
    this.mainTables = [];
    this.detailIndex = {};
    this.fieldIndex = {};
    this.fieldName = {};
    this.loading = false;
}

export function isInDetails(mainTable, row, col) {
    let bool = false;
    mainTable.detailTables.forEach(area => {
        if (row >= area.row && row < area.row + area.rowCount && col >= area.col && col < area.col + area.colCount) {
            bool = true;
        }
    });
    return bool;
}
export function clearContent() {
    const sheet = this.workbook.getActiveSheet();
    const selections = sheet.getSelections();
    const sheetName = sheet.name();
    this.workbook.commandManager().execute({
        autoFitType: GC.Spread.Sheets.AutoFitType.cell,
        cmd: 'clearContent',
        sheet,
        sheetName,
        selections
    });
}
export function addDetailTable() {
    this.includeTitle = "1";
    Modal.confirm({
        content: (
            <div>
                <WeaCheckbox
                    id='test'
                    value={this.includeTitle}
                    onChange={(value) => {
                        this.includeTitle = value;
                    }}
                />
                <span style={{ marginLeft: 10 }}>{getLabel('502908', '包含标题')}</span>
            </div>
        ),
        onOk: this.addDetailTableAction
    });
}

export function addNoDetailTable() {
    this.includeTitle = "";
    this.addNoDetailTableAction();
}

export function deleteTable() {
    const sheet = this.workbook.getActiveSheet();
    const sheetIndex = this.workbook.getActiveSheetIndex();
    const sheetName = sheet.name();
    const row = sheet.getActiveRowIndex();
    const col = sheet.getActiveColumnIndex();
    const table = sheet.tables.find(row, col);
    if (table) {
        this.workbook.commandManager().execute({
            autoFitType: GC.Spread.Sheets.AutoFitType.cell,
            cmd: 'deleteDetailCard',
            sheet,
            sheetIndex,
            sheetName,
            table
        });

    }
}
export function addDetailTableAction() {
    const sheet = this.workbook.getActiveSheet();
    const sheetIndex = this.workbook.getActiveSheetIndex();
    const sheetName = sheet.name();
    const mainTableObj = this.mainTables[sheetIndex] ? this.mainTables[sheetIndex] : {
        detailTables: [],
        fields: [],
        sheetName,
        tableName: `${this.title}${sheetName}`
    };
    this.mainTables[sheetIndex] = mainTableObj;
    const selections = sheet.getSelections();

    this.workbook.commandManager().execute({
        autoFitType: GC.Spread.Sheets.AutoFitType.cell,
        cmd: 'addDetailCard',
        sheet,
        sheetIndex,
        sheetName,
        selections,
        mainTableObj: this.mainTables[sheetIndex],
        getDetailIndex: this.getDetailIndex,
        getFieldIndex: this.getFieldIndex,
        getFieldCellType: getFieldCellType,
        getFieldName: this.getFieldName,
        includeTitle: this.includeTitle,
        nodetailJson: this.nodetailJson,
    });
}

// 设置非明细区域
export function addNoDetailTableAction() {
    const sheet = this.workbook.getActiveSheet();
    const sheetIndex = this.workbook.getActiveSheetIndex();
    const sheetName = sheet.name();
    const mainTableObj = this.mainTables[sheetIndex] ? this.mainTables[sheetIndex] : {
        detailTables: [],
        fields: [],
        sheetName,
        tableName: `${this.title}${sheetName}`
    };
    this.mainTables[sheetIndex] = mainTableObj;
    const selections = sheet.getSelections();
    this.workbook.commandManager().execute({
        autoFitType: GC.Spread.Sheets.AutoFitType.cell,
        cmd: 'addNoDetailCard',
        sheet,
        sheetIndex,
        sheetName,
        selections,
        mainTableObj: this.mainTables[sheetIndex],
        getDetailIndex: this.getDetailIndex,
        getFieldIndex: this.getFieldIndex,
        getFieldCellType: getFieldCellType,
        getFieldName: this.getFieldName,
        includeTitle: this.includeTitle,
        nodetailJson: this.nodetailJson,
    });
}

export function setCellTypeProps(key, value) {
    const FieldCellType = CellType('FieldCellType');
    const sheet = this.workbook.getActiveSheet();
    const row = sheet.getActiveRowIndex();
    const col = sheet.getActiveColumnIndex();
    const cell = sheet.getCell(row, col);
    const cellType = cell.cellType();
    if (cellType instanceof FieldCellType) {
        cellType[key] = value;
    }
}

export function setAutoFillin(bool) {
    this.isAutoFillin = bool;
    const sheet = this.workbook.getActiveSheet();
    const row = sheet.getActiveRowIndex();
    const col = sheet.getActiveColumnIndex();
    const cell = sheet.getCell(row, col);
    const cellType = cell.cellType();
    if (cellType instanceof FieldCellType) {
        cellType.autoFillin = bool;
    }
}

export function addDataSource() {
    const { id: pageid = '', name } = this.page || {}
    this.dataSourceStore.newDataSource(pageid, name);
}
export function openDataSource(uuid) {
    const { id: pageid = '', name } = this.page || {}
    this.dataSourceStore.openDataSource(pageid, name, uuid);
}

export function addFieldAssign() {
    const { id: pageid = '', name } = this.page || {}
    this.fieldAssignStore.newFieldAssign(pageid, name);
}

export function openFieldAssign(uuid) {
    const { id: pageid = '', name } = this.page || {}
    this.fieldAssignStore.openFieldAssign(pageid, name, uuid);
}

export function deleteFieldAssign(uuid) {
    this.fieldAssignStore.deleteFieldAssign(uuid);
}

export function deleteDataSource(uuid) {
    this.dataSourceStore.deleteDataSource(uuid);
}
